import dotenv from "dotenv"
import express from "express"
import cors from "cors"
import colors from "colors"
import path from "path"
import { notFound, errorHandler } from "./middleware/error.js"
import connectDB from './config/db.js'
import productsRoute from "./routes/product.js"
import userRouter from './routes/user.js'
import orderRouter from './routes/order.js'
import uploadRouter from './routes/uploads.js'
import cartRouter from "./routes/cart.js"

/* 引入环境变量 */
dotenv.config({ path: './.env.local' })
const app = express()
/* 跨域 */
app.use(cors());
/* 设置接受json */
app.use(express.json())

/* 连接数据库 */
connectDB()

/* 设置静态文件夹 */
const __dirname = path.resolve()
app.use('/uploads', express.static(path.join(__dirname, '/uploads')))

/* api路由 */
app.use('/api/user',userRouter)
app.use('/api/product',productsRoute)
app.use('/api/order',orderRouter)
app.use('/api/upload',uploadRouter)
app.use('/api/cart',cartRouter)


/* 自定义错误中间件 */
app.use(notFound)
app.use(errorHandler)

const PORT = process.env.PORT
app.listen(PORT, () => {
  console.log(`服务器已经在${PORT}端口运行, 环境为${process.env.NODE_ENV}`.yellow.bold)
})